/**********************************************************************
Compile : gcc -O3 -o random1 random1.c
Usage   : ./random1 mode N L M n seed       
mode    : 0 common; 1 cycled; 2: triggled cycle
N       : number of the nodes                
L       : number of the steps        
M       : the number of "1" in the process  
n       : the number of the attempts         
seed    : random seed
***********************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

void print_help ()
{
	printf ("Usage         : ./random1 mode N L M n seed\n");
	printf ("                (./random1 0 11 12 41 10000 $RANDOM)\n");
	printf ("mode          : 0 common; 1 cycled; 2: triggled cycle\n");
	printf ("N             : number of the nodes\n");
	printf ("L             : number of the steps\n");
	printf ("M             : the number of \"1\" in the process\n");
	printf ("n             : the number of processes that want to generate\n");
	printf ("seed          : random seed\n");
}

void generate_pathway2 (int N, int L, int M, int pathway[L][N], int mode)
{
	int i, j, n1, n2, flag;
	float ratio;

	do
	{
		n1 = N * (L - 1);
		n2 = M;
		for (i = 0; i < N; i++)
		{
			flag = 0;

			if (n2 < N - i)
				break;

			for (j = 0; j < L - 1; j++)
			{
				ratio = (float) n2 / (float) n1;
				if (drand48 () < ratio)
				{
					pathway[j][i] = 1;
					flag ++;
					n2 --;
				}
				else
					pathway[j][i] = 0;
				n1 --;
			}
			if (flag == 0 || flag == L - 1)
			{
				break;
			}
		}
	}
	while (flag == 0 || flag == L - 1);

	for (i = 0; i < N; i++)
	{
		if (mode == 0)
			pathway[L - 1][i] = pathway[L - 2][i];
		else if (mode == 1)
			pathway[L - 1][i] = pathway[0][i];
	}
}

void generate_pathway (int N, int L, int M, int pathway[L][N], int mode)
{
	if (mode != 2)
		generate_pathway2 (N, L, M, pathway, mode);
	else
	{
		int i, j;
		int pathway2[L - 1][N - 1];

		generate_pathway2 (N - 1, L - 1, M, pathway2, 0);

		pathway[0][0] = 1;
		for (i = 1; i < L; i++)
		{
			pathway[i][0] = 0;
		}

		for (i = 0; i < L - 1; i++)
		{
			for (j = 0; j < N - 1; j++)
			{
				pathway[i + 1][j + 1] = pathway2[i][j];
			}
		}

		for (i = 1; i < N; i++)
		{
			pathway[0][i] = pathway2[L - 2][i - 1];
		}
	}
}

int main (int argc, char *argv[])
{
	long int seed, n;
	int N, L, M, i, j, k, mode;

	if (argc == 1)
	{
		print_help ();
		exit (0);
	}

	mode = atoi (argv[1]);
	N = atoi (argv[2]);
	L = atoi (argv[3]);
	M = atoi (argv[4]);
	n = atoi (argv[5]);
	seed = atoi (argv[6]);
	srand48 (seed);
	//printf ("Random Seed : %ld\tAttempts : %ld\n", seed, n);

	int pathway[L][N];

	for (i = 0; i < n; i++)
	{
		generate_pathway (N, L, M, pathway, mode);

		printf ("c candidate process %d\n", M);
                
		for (j = 0; j < L; j++)
		{
			for (k = 0; k < N; k++)
			{
				printf ("%d ", pathway[j][k]);
			}
			printf ("\n");
		}
	}

	exit (0);
}
